/**
 * 全局错误处理中间件
 * Global Error Handler Middleware
 */

const logger = require('../utils/logger');

const errorHandler = (err, req, res, next) => {
  let error = { ...err };
  error.message = err.message;

  // 记录错误日志
  logger.error(`错误发生在 ${req.method} ${req.path}`, {
    error: err.message,
    stack: err.stack,
    ip: req.ip,
    userAgent: req.get('User-Agent')
  });

  // 默认错误响应
  let statusCode = 500;
  let message = '服务器内部错误 / Internal Server Error';

  // 处理特定类型的错误
  if (err.name === 'ValidationError') {
    statusCode = 400;
    message = '请求参数验证失败 / Request validation failed';
  } else if (err.name === 'UnauthorizedError' || err.name === 'JsonWebTokenError') {
    statusCode = 401;
    message = '未授权访问 / Unauthorized access';
  } else if (err.name === 'ForbiddenError') {
    statusCode = 403;
    message = '权限不足 / Insufficient permissions';
  } else if (err.name === 'NotFoundError') {
    statusCode = 404;
    message = '资源不存在 / Resource not found';
  } else if (err.code === 'LIMIT_FILE_SIZE') {
    statusCode = 413;
    message = '文件大小超出限制 / File size exceeds limit';
  } else if (err.code === 'LIMIT_UNEXPECTED_FILE') {
    statusCode = 400;
    message = '不支持的文件类型 / Unsupported file type';
  } else if (err.code === 'ENOSPC') {
    statusCode = 507;
    message = '存储空间不足 / Insufficient storage space';
  } else if (err.code === 'ER_DUP_ENTRY') {
    statusCode = 409;
    message = '数据已存在 / Data already exists';
  } else if (err.code === 'ER_NO_REFERENCED_ROW_2') {
    statusCode = 400;
    message = '关联数据不存在 / Referenced data does not exist';
  } else if (err.code === 'ECONNREFUSED') {
    statusCode = 503;
    message = '数据库连接失败 / Database connection failed';
  }

  // 如果有自定义状态码，使用自定义的
  if (err.statusCode) {
    statusCode = err.statusCode;
  }

  // 如果有自定义消息，使用自定义的
  if (err.message && process.env.NODE_ENV === 'development') {
    message = err.message;
  }

  // 构建错误响应
  const errorResponse = {
    success: false,
    error: {
      message,
      statusCode
    }
  };

  // 开发环境下包含更多错误信息
  if (process.env.NODE_ENV === 'development') {
    errorResponse.error.stack = err.stack;
    errorResponse.error.details = err;
  }

  res.status(statusCode).json(errorResponse);
};

// 处理未捕获的异常
process.on('uncaughtException', (err) => {
  logger.error('未捕获的异常 / Uncaught Exception', {
    error: err.message,
    stack: err.stack
  });
  process.exit(1);
});

// 处理未处理的Promise拒绝
process.on('unhandledRejection', (err, promise) => {
  logger.error('未处理的Promise拒绝 / Unhandled Promise Rejection', {
    error: err.message,
    stack: err.stack
  });
});

module.exports = errorHandler;